<template>
  <div
    style="display: flex; flex-direction: column; align-items: center; flex: 1"
    class="animate__animated animate__fadeInLeft"
  >
    <h3 class="place-holder">修改密码</h3>
    <el-form
      label-width="90px"
      ref="resetForm"
      :model="resetForm"
      :rules="resetFormRules"
    >
      <el-form-item label="旧密码:" prop="password">
        <el-input
          placeholder="请输入旧密码"
          show-password
          v-model="resetForm.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码:" prop="new_password">
        <el-input
          placeholder="请输入新密码"
          show-password
          v-model="resetForm.new_password"
        ></el-input>
      </el-form-item>
      <el-form-item label="重复密码:" prop="new_password1">
        <el-input
          placeholder="请输入重复密码"
          show-password
          v-model="resetForm.new_password1"
        >
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { set } from "@/utils/store";
// import { watch } from "vue";
import { mapActions, mapState } from "vuex";

export default {
  name: "UserInfoPassword",
  props: {},
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else if (value.toString().length < 6 || value.toString().length > 18) {
        callback(new Error("密码长度为6-18位"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.resetForm.new_password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      resetForm: {
        //传给后台所需要的参数
        //新密码
        new_password: "",
        //旧密码
        password: "",
      },
      resetFormRules: {
        password: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        new_password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        new_password1: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
      },
    };
  },
  // watch: {
  //   newpwd(val) {
  //     this.resetForm.password = val;
  //   },
  // },
  computed: {
    ...mapState("user", ["userinfo"]),
  },
  methods: {
    ...mapActions("user", ["editPassword"]),
    async save() {
      await this.$refs.resetForm.validate((valid) => {
        if (valid) {
          try {
            this.editPassword(this.resetForm);
            this.resetForm.new_password = set("password");
            this.$router.push("/login");
            this.$message({
              message: "修改成功",
              type: "success",
            });
          } catch (err) {
            this.$message.error("修改失败");
          }
        }
      });
    },
  },
};
</script>
